﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Dropthings.Widget.Framework;
using Dropthings.Widget.Widgets;
using Dropthings.Widget.Widgets.FusionCharts;
using InfoSoftGlobal;
using Dropthings.Util;
using Dropthings.Business.Facade;
using Dropthings.Business.Facade.Context;
using System.Collections.Generic;
using System.Text;

public partial class FusionChart_Gas : System.Web.UI.UserControl, IWidget
{
    #region Fields

    private IWidgetHost _Host;
    private XElement _State;
    private XElement State
    {
        get
        {
            if (_State == null)
            {
                string stateXml = this._Host.GetState();
                if (string.IsNullOrEmpty(stateXml))
                {
                    _State = new XElement("state",
                        new XElement("year", DateTime.Now.Year.ToString()),
                        new XElement("month",DateTime.Now.Month.ToString()),
                        new XElement("day",(DateTime.Now.Day-1)),
                        new XElement("orgnaziationCode", ""));
                }
                else
                {
                    _State = XElement.Parse(stateXml);
                }
            }
            return _State;
        }
    }

    public int ShowYear
    {
        get { return State.Element("year") == null ? DateTime.Now.Year : int.Parse(State.Element("year").Value); }
        set
        {
            if (State.Element("year") == null)
                State.Add(new XElement("year", value));
            else
                State.Element("year").Value = value.ToString();
        }
    }
    public string ShowBuildingCode
    {
        get { return State.Element("orgnaziationCode") == null ? "001" : State.Element("orgnaziationCode").Value; }
        set
        {
            if (State.Element("orgnaziationCode") == null)
                State.Add(new XElement("orgnaziationCode", value));
            else
                State.Element("orgnaziationCode").Value = value;
        }
    }
    public int ShowMonth
    {
        get { return (State.Element("month") == null||State.Element("month").Value=="0") ? DateTime.Now.Month : int.Parse(State.Element("month").Value); }
        set
        {
            if (State.Element("month") == null)
                State.Add(new XElement("month", value));
            else
                State.Element("month").Value = value.ToString();
        }

    }
    public int ShowDay
    {
        get { return (State.Element("day") == null||State.Element("day").Value=="0") ? (DateTime.Now.Day) : int.Parse(State.Element("day").Value); }
        set
        {
            if (State.Element("day") == null)
                State.Add(new XElement("day", value));
            else
                State.Element("day").Value = value.ToString();
        }
    }
    public int ShowType
    {
        get { return State.Element("type") == null ? 1 : int.Parse(State.Element("type").Value); }
        set
        {
            if (State.Element("type") == null)
                State.Add(new XElement("type", value));
            else
                State.Element("type").Value = value.ToString();
        }
    }

    #endregion Fields

    #region IWidget接口实现
    void IEventListener.AcceptEvent(object sender, EventArgs e)
    {
        
    }

    void IWidget.Closed()
    {
    }

    void IWidget.Collasped()
    {
    }

    void IWidget.Expanded()
    {
    }

    void IWidget.HideSettings(bool userClicked)
    {
        SettingsPanel.Visible = false;
        if (userClicked)
        {
            ShowLinkBtn(true);
            this.ShowBuildingCode = BuildingDropDownList.SelectedValue;
            this.ShowType = int.Parse(rblType.Value);
            if (rblType.Value == "1")
            {
                this.ShowYear = int.Parse(ddl1Year.SelectedValue);
                this.ShowMonth = 0;
                this.ShowDay = 0;
            }
            else if (rblType.Value == "2")
            {
                this.ShowYear = int.Parse(ddl2Year.SelectedValue);
                this.ShowMonth = int.Parse(ddl2Month.SelectedValue);
                this.ShowDay = 0;
            }
            else if (rblType.Value == "3")
            {
                this.ShowYear = int.Parse(ddl3Year.SelectedValue);
                this.ShowMonth = int.Parse(ddl3Month.SelectedValue);
                this.ShowDay = int.Parse(HttpContext.Current.Request[ddl3Day.UniqueID]);
            }
        }
        this.SaveState();
    }

    void IWidget.Init(IWidgetHost host)
    {
        this._Host = host;
    }

    void IWidget.Maximized()
    {
    }

    void IWidget.Restored()
    {
    }

    void IWidget.ShowSettings(bool userClicked)
    {
        SettingsPanel.Visible = true;
        if (userClicked)
        {
            ShowDDLControl(rblType.Value);
            ShowLinkBtn(false);
            if (rblType.Value == "1")
            {
                if (ddl1Year.Items.Count == 0)
                {
                    for (int i = 2000; i <= DateTime.Now.Year; i++)
                    {
                        ddl1Year.Items.Add(new ListItem(i.ToString()));
                    }
                }
                ddl1Year.SelectedIndex = -1;
                ddl1Year.Items.FindByText(this.ShowYear.ToString()).Selected = true;
            }
            else if (rblType.Value == "2")
            {
                if (ddl2Year.Items.Count == 0)
                {
                    for (int i = 2000; i <= DateTime.Now.Year; i++)
                    {
                        ddl2Year.Items.Add(new ListItem(i.ToString()));
                    }
                }
                ddl2Year.SelectedIndex = -1;
                ddl2Year.Items.FindByText(this.ShowYear.ToString()).Selected = true;
                ddl2Month.SelectedIndex = -1;
                ddl2Month.Items.FindByValue(this.ShowMonth.ToString()).Selected = true;
            }
            else if (rblType.Value == "3")
            {
                if (ddl3Year.Items.Count == 0)
                {
                    for (int i = 2000; i <= DateTime.Now.Year; i++)
                    {
                        ddl3Year.Items.Add(new ListItem(i.ToString()));
                    }
                }
                ddl3Year.SelectedIndex = -1;
                ddl3Year.Items.FindByText(this.ShowYear.ToString()).Selected = true;
                ddl3Month.SelectedIndex = -1;
                ddl3Month.Items.FindByValue(this.ShowMonth.ToString()).Selected = true;
                ddl3Day.Items.Clear();
                int dayCount = getDayCount();
                for (int i = 1; i <= dayCount; i++)
                {
                    ddl3Day.Items.Add(new ListItem(i.ToString()));
                }
                ddl3Day.SelectedIndex = -1;
                ddl3Day.Items.FindByValue(this.ShowDay.ToString()).Selected = true;
            }
         
            BuildingDropDownList.SelectedIndex = -1;
            if (BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode) != null)
                BuildingDropDownList.Items.FindByValue(this.ShowBuildingCode).Selected = true;
        }
    }
    #endregion

    #region 页面事件处理
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (string.IsNullOrEmpty(rblType.Value))
            rblType.Value = this.ShowType.ToString();
        SetLinkBtnStyle(rblType.Value);
        ShowChartByType(rblType.Value);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (BuildingDropDownList.Items.Count == 0)
        {
            Dictionary<string, string> allBuildings = getAllBuildings();
            foreach (string key in allBuildings.Keys)
            {
                ListItem item = new ListItem();
                item.Text = allBuildings[key];
                item.Value = key;
                BuildingDropDownList.Items.Add(item);
            }
            if (BuildingDropDownList.Items.Count > 0)
                this.ShowBuildingCode = BuildingDropDownList.Items[0].Value;
        }

    }

    protected void SaveSettings_Click(object sender, EventArgs e)
    {
        _Host.HideSettings(true);
    }

    protected void lbtnYear_Click(object sender, EventArgs e)
    {
        rblType.Value = "1";
        this._Host.Refresh(this);
    }

    protected void lbtnMonth_Click(object sender, EventArgs e)
    {
        rblType.Value = "2";
        this._Host.Refresh(this);
    }

    protected void lbtnDay_Click(object sender, EventArgs e)
    {
        rblType.Value = "3";
        this._Host.Refresh(this);
    }
    #endregion

    #region 页面处理方法
    private void ShowChartByType(string type)
    {
        if (type == "1")
        {
            ShowYearChart();
        }
        else if (type == "2")
        {
            ShowMonthChart();
        }
        else if (type == "3")
        {
            ShowDayChart();
        }
    }

    private void ShowDDLControl(string type)
    {
        tdTable1.Visible = type == "1" ? true : false;
        tdTable2.Visible = type == "2" ? true : false;
        tdTable3.Visible = type == "3" ? true : false;
    }

    private void ShowLinkBtn(bool b)
    {
        lbtnYear.Enabled = b;
        lbtnMonth.Enabled = b;
        lbtnDay.Enabled = b;
    }

    private void SetLinkBtnStyle(string str)
    {
        if (str == "1")
        {
            lbtnYear.Attributes["style"] = "color:red;text-decoration:underline;";
            lbtnMonth.Attributes.Remove("style");
            lbtnDay.Attributes.Remove("style");
        }
        else if (str == "2")
        {
            lbtnMonth.Attributes["style"] = "color:red;text-decoration:underline;";
            lbtnYear.Attributes.Remove("style");
            lbtnDay.Attributes.Remove("style");
        }
        else if (str == "3")
        {
            lbtnDay.Attributes["style"] = "color:red;text-decoration:underline;";
            lbtnMonth.Attributes.Remove("style");
            lbtnYear.Attributes.Remove("style");
        }

    }

    private void SaveState()
    {
        var xml = this.State.Xml();
        this._Host.SaveState(xml);
        this._State = null;
    }

    private void ShowYearChart()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("<chart caption='天然气月耗图' subcaption='{0}年' xAxisName='月份' yAxisName='立方米' showNames='1' ", ShowYear);
        sb.Append("animation='1' baseFontColor='666666' showLegend='0' useRoundEdges='1'>");
        sb.Append("<categories>");
        sb.Append("<category label='一月' />");
        sb.Append("<category label='二月' />");
        sb.Append("<category label='三月' />");
        sb.Append("<category label='四月' />");
        sb.Append("<category label='五月' />");
        sb.Append("<category label='六月' />");
        sb.Append("<category label='七月' />");
        sb.Append("<category label='八月' />");
        sb.Append("<category label='九月' />");
        sb.Append("<category label='十月' />");
        sb.Append("<category label='十一月' />");
        sb.Append("<category label='十二月' />");
        sb.Append("</categories>");
        sb.AppendFormat("<dataset seriesName='' >");
        DataSet datasDS = getMonthDatasInYear(ShowYear,ShowBuildingCode);
        for (int i = 1; i <= 12; i++)
        {
            string strData = "<set value='' />";
            if (datasDS != null && datasDS.Tables.Count > 0 && datasDS.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in datasDS.Tables[0].Rows)
                {
                    int time = Convert.ToInt32(dr["ReadingMonth"]);
                    if (i == time)
                    {
                        strData = string.Format("<set value='{0}' />",Convert.ToDouble(dr["MonthData"]));
                        break;
                    }
                }
            }
            sb.Append(strData);
        }
        sb.Append("</dataset>");
        sb.Append("</chart>");
        Literal1.Text = FusionCharts.RenderChartHTML("../FusionCharts/ScrollColumn2D.swf", "", sb.ToString(), "myFirst", "100%", "267", false, false);
    }

    private void ShowMonthChart()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("<chart caption='天然气日耗图' subcaption='{0}年{1}月' xAxisName='日' yAxisName='立方米' showNames='1' ", ShowYear, ShowMonth);
        sb.Append("animation='1' baseFontColor='666666' showLegend='0' useRoundEdges='1'>");
        sb.Append("<categories>");
        for (int i = 1; i <= getDayCount(); i++)
        {
            sb.AppendFormat("<category label='{0}' />", i);
        }
        sb.Append("</categories>");
        DataSet datasDS = getDayDatasInMonth(ShowYear, ShowMonth, ShowBuildingCode);
        sb.AppendFormat("<dataset seriesName='' >");
        for (int i = 1; i <= getDayCount(); i++)
        {
            string strData = "<set value='' />";
            if (datasDS != null && datasDS.Tables.Count > 0 && datasDS.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in datasDS.Tables[0].Rows)
                {
                    int time = Convert.ToInt32(dr["ReadingDay"]);
                    if (i == time)
                    {
                        strData = string.Format("<set value='{0}' />",Convert.ToDouble(dr["DayTotalData"]));
                        break;
                    }
                }
            }
            sb.Append(strData);
        }
        sb.Append("</dataset>");
        sb.Append("</chart>");
        Literal1.Text = FusionCharts.RenderChartHTML("../FusionCharts/ScrollColumn2D.swf", "", sb.ToString(), "myFirst", "100%", "267", false, false);
    }

    private void ShowDayChart()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("<chart caption='天然气时耗图' subcaption='{0}年{1}月{2}日' xAxisName='时间' yAxisName='立方米' showNames='1' ", ShowYear, ShowMonth, ShowDay);
        sb.Append("animation='1' baseFontColor='666666' lineAlpha='85' useRoundEdges='1'>");
        sb.Append("<categories>");
        for (int i = 0; i < 24; i++)
        {
            sb.AppendFormat("<category label='{0}:00' />", i);
        }
        sb.Append("</categories>");
        Dictionary<string, double[]> values = getDatasForDayChart(ShowYear, ShowMonth, ShowDay, ShowBuildingCode);
        if (values.Keys.Count > 0)
        {
            foreach (string key in values.Keys)
            {
                sb.AppendFormat("<dataset seriesName='{0}' >", key);
                double[] keyValue = values[key];
                for (int i = 0; i < keyValue.Length; i++)
                {
                    if (keyValue[i] == -1)
                        sb.Append("<set value='' />");
                    else
                        sb.AppendFormat("<set value='{0}' />", keyValue[i]);
                }
                sb.Append("</dataset>");
            }
        }
        sb.Append("</chart>");
        Literal1.Text = FusionCharts.RenderChartHTML("../FusionCharts/ScrollLine2D.swf", "", sb.ToString(), "myFirst", "100%", "267", false, false);
    }

    #endregion

    private Dictionary<string, string> getAllBuildings()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            Dictionary<string, string> allBuildings = new Dictionary<string, string>();
            DataSet ds = facade.GetOrganizeBaseInfo();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string name = Convert.ToString(dr["OrganizeName"]);
                    string key = Convert.ToString(dr["OrganizeIdentify"]);
                    allBuildings.Add(key, name);
                }
            }
            return allBuildings;
        }
    }

    private Dictionary<string, double[]> getDatasForDayChart(int year, int month, int day,string buildingCode)
    {
        Dictionary<string, double[]> values = new Dictionary<string, double[]>();
        double[] GasDatasInWorkTime = getHourDatasInDay(year, month,day, buildingCode,true);
        double[] GasDatasNotinWorkTime = getHourDatasInDay(year, month, day, buildingCode, false);
        values.Add("工作时间", GasDatasInWorkTime);
        values.Add("非工作时间", GasDatasNotinWorkTime);
        return values;
    }

    private DataSet getMonthDatasInYear(int year,string buildingCode)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetGasMonthDatasInYear(buildingCode, year);
            return ds;
        }
    }

    private DataSet getDayDatasInMonth(int year, int month, string buildingCode)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetGasDayDatasInMonth(buildingCode, year, month);
            return ds;
        }
    }

    private double[] getHourDatasInDay(int year, int month,int day, string buildingCode, bool isWorkTime)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            double[] TimeDatas = new double[24];
            for (int i = 0; i < TimeDatas.Length; i++)
            {
                TimeDatas[i] = -1;
            }
            DataSet ds = facade.GetGasTimeDatasInWorkTimeOrNot(buildingCode, year, month, day,isWorkTime);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    int time = Convert.ToInt32(dr["ReadingTime"]);
                    double dayData = Convert.ToDouble(dr["TimeTotalData"]);
                    TimeDatas[time] = dayData;
                }
            }
            return TimeDatas;
        }
    }

    private int getDayCount()
    {
        int count = 31;
        if (ShowMonth == 2)
        {
            if (ShowYear % 400 == 0 || ((ShowYear % 100 != 0) && (ShowYear % 4 == 0)))
                count = 29;
            else
                count = 28;
        }
        else if (ShowMonth == 4 || ShowMonth == 6 || ShowMonth == 9 || ShowMonth == 11)
        {
            count = 30;
        }
        return count;
    }

}